<template>
    <div>
        <SuperTable ref="table" path="/admin/index" :params="params" :columns="columns">
            <Button slot="header-left" type="primary" @click="showModal = true">添加管理员</Button>
        </SuperTable>
        <Modal :title="form.id ? '编辑管理员' : '添加管理员'" v-model="showModal" :width="350" @on-cancel="handleCancel">
            <Form ref="form" :model="form" :rules="rules" :label-width="60" >
                <FormItem label="用户名" prop="username">
                    <Input v-model="form.username" />
                </FormItem>
                <FormItem label="密码" prop="password">
                    <Input type="password" v-model="form.password" clearable />
                </FormItem>
                <FormItem label="角色" prop="role_id" required>
                    <Select v-model="form.role_id">
                        <Option v-for="item in roles" :key="item.id" :value="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>
                <FormItem label="姓名" prop="realname">
                    <Input v-model="form.realname" />
                </FormItem>
                <FormItem label="头像" prop="avatar">
                    <ImageUpload v-model="form.avatar"></ImageUpload>
                </FormItem>
                <FormItem label="状态" prop="status" required>
                    <RadioGroup v-model="form.status">
                        <Radio :label="1">启用</Radio>
                        <Radio :label="0">禁用</Radio>
                    </RadioGroup>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button :disabled="submiting" @click="handleCancel">取消</Button>
                <Button type="primary" :loading="submiting" @click="handleSubmit">提交</Button>
            </div>
        </Modal>
    </div>
</template>

<script>
import SuperTable from '@/components/utils/super-table.vue';
import TableRows from '@/components/utils/table-rows.vue';
import ImageUpload from '@/components/form/image-upload.vue';
export default {
    components: {
        SuperTable,
        TableRows,
        ImageUpload
    },
    data() {
        return {
            roles: [],
            submiting: false,
            showModal: false,
            form: {
                id: '',
                role_id: 0,
                username: '',
                password: '',
                realname: '',
                avatar: '',
                status: 1,
            },
            rules: {
                username: [
                    {required: true, message: '请输入用户名', trigger: 'blur'}
                ],
                password: [
                    {required: true, message: '请输入密码', trigger: 'blur'}
                ],
                realname: [
                    {required: true, message: '请输入真实姓名', trigger: 'blur'}
                ],
                role_id: [
                    {required: true, type: "number", message: "请选择角色", trigger: "change"}
                ],
            },
            params: {
                page: 1,
                pageSize: 10
            },
            columns: [
                {
                    title: '用户信息',
                    render: (h, params) => {
                        return h(TableRows, {
                            props: {
                                src: params.row.avatar || '/static/images/default_avatar.png'
                            }
                        }, [
                            h('p',`用户名：${params.row.username}`),
                            h('p',`姓名：${params.row.realname}`)
                        ])
                    }
                },
                {
                    title: '角色&状态',
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`角色：${params.row.role ? params.row.role.name : ''}`),
                            h('p',`状态：${params.row.status_text}`),
                        ])
                    }
                },
                {
                    title: '最后登录IP&时间',
                    minWidth: 150,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`${params.row.login_ip || ''}`),
                            h('p',`${params.row.login_time || ''}`),
                        ])
                    }
                },
                {
                    title: '创建&更新时间',
                    minWidth: 150,
                    render: (h, params) => {
                        return h(TableRows,[
                            h('p',`${params.row.created_at}`),
                            h('p',`${params.row.updated_at}`),
                        ])
                    }
                },
                {
                    title: "操作",
                    align: "center",
                    key: "action",
                    width: 140,
                    render: (h, params) => {
                        return h("div", [
                            h("Button", {
                                props: {
                                    type: "success",
                                    size: "small",
                                    disabled: params.row.id == 1
                                },
                                on: {
                                    click: () => {
                                        this.showModal = true;
                                        this.form.id = params.row.id;
                                        this.form.role_id = params.row.role_id;
                                        this.form.username = params.row.username;
                                        this.form.password = '';
                                        this.form.realname = params.row.realname;
                                        this.form.avatar = params.row.avatar;
                                        this.form.status = params.row.status;
                                    }
                                }
                            }, "编辑"),
                            h("Button", {
                                style: {
                                    marginLeft: "5px"
                                },
                                props: {
                                    type: "error",
                                    size: "small",
                                    disabled: params.row.id == 1
                                },
                                on: {
                                    click: () => {
                                        this.handleDelete(params.row);
                                    }
                                }
                            }, "删除")
                        ]);
                    }
                }
            ]
        }
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            // 角色数据
            this.$ajax.get('/admin/role/index', {params: {page: 1, pageSize: 100}}).then(res => {
                this.roles = res.items.filter(item => item.id !== 1);
            }).catch(() => {
                // todo
            })
        },
        handleDelete(row) {
            this.$Modal.confirm({
                title: "操作提示:",
                width: 320,
                content: `<p>您确定要删除管理员‘${row.username}’吗?</p>`,
                onOk: () => {
                    const msg = this.$Message.loading({
                        content: '正在提交删除',
                        duration: 0
                    });
                    this.$ajax.delete('/admin/delete', {params: {ids: [row.id]}}).then(() => {
                        msg();
                        this.$Message.success('删除成功');
                        this.$refs.table.reload();
                    }).catch(err => {
                        msg();
                        this.$Message.error(err.message || '删除失败');
                    })
                }
            });
        },
        handleSubmit() {
            if(this.submiting) return false;
            this.$refs.form.validate((valid) => {
                if(valid) {
                    const { form } = this;
                    let params = {
                        role_id: form.role_id,
                        username: form.username,
                        password: form.password,
                        realname: form.realname,
                        avatar: form.avatar,
                        status: form.status,
                    }
                    this.submiting = true;
                    if (form.id) {
                        this.$ajax.put('/admin/update/'+form.id, params).then(res => {
                            this.$Message.success('编辑成功');
                            this.handleCancel();
                            this.$refs.table.reload();
                            this.submiting = false;
                        }).catch(err => {
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }else{
                        this.$ajax.post('/admin/save', params).then(res => {
                            this.$Message.success('添加成功');
                            this.handleCancel();
                            this.$refs.table.init();
                            this.submiting = false;
                        }).catch(err => {
                            this.submiting = false;
                            this.$Message.error(err.message || '提交失败');
                        })
                    }
                }
            })
        },
        handleCancel() {
            this.showModal = false;
            setTimeout(() => {
                this.form.id = '';
                this.form.role_id = 0;
                this.form.username = '';
                this.form.password = '';
                this.form.realname = '';
                this.form.avatar = '';
                this.form.status = 1;
            }, 300)
        }
    }
}
</script>